package com.yzf.demo.demo.Thread;

import java.util.concurrent.*;

/**
 * Created by 于占峰 on 2020/4/4/004.
 * CallableFuture的使用
 */
public class CallableFutureDemo implements Callable<String> {
    @Override
    public String call() throws Exception {
        System.out.println("Hell gebiulaoyu");
        Thread.sleep(3000);//睡眠三秒
        return "返回值";
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //构建要执行的线程对象
        CallableFutureDemo callableFutureDemo = new CallableFutureDemo();
        //构建FutureTask 将要执行的线程对象传入
        FutureTask futureTask = new FutureTask(callableFutureDemo);
        //创建一个线程来运行futureTask
        new Thread(futureTask).start();
        //futureTask.get方法是阻塞的 必须等整个任务执行完毕才能拿到返回值
        // 否则这个线程会一直处于阻塞状态而一直拿不到结果
        System.out.println(futureTask.get());

        /**
         * 线程池执行FutureTask
         */
        //侯建一个线程池
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        //构建要执行的线程对象
        CallableFutureDemo callableFutureDemo1 = new CallableFutureDemo();
        //将实现Callable接口的对象传入线程池执行 返回 FutureTask
        //executorService.submit 其底层实现原理和上面是一样的
        FutureTask futureTask2 = (FutureTask) executorService.submit(callableFutureDemo1);
        System.out.println(futureTask2.get());

    }
}
